package com.weilf.zookeeper.simple;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @author weil-f
 * @date 2021/2/6 8:57
 */
public class MyZookeeper {
	public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
		final CountDownLatch countDownLatch = new CountDownLatch(1);
		final ZooKeeper zkClient = new ZooKeeper("192.168.6.29:2181", 5000, new Watcher() {
			public void process(WatchedEvent watchedEvent) {
				Event.EventType type = watchedEvent.getType();
				Event.KeeperState state = watchedEvent.getState();
				System.out.println("创建zookeeper 的监听"+watchedEvent.toString());
				switch (type) {
					case None:
						break;
					case NodeCreated:
						break;
					case NodeDeleted:
						break;
					case NodeDataChanged:
						break;
					case NodeChildrenChanged:
						break;
				}
				switch (state) {
					case Unknown:
						break;
					case Disconnected:
						break;
					case NoSyncConnected:
						break;
					case SyncConnected:
						System.out.println("connected");
						countDownLatch.countDown();
						break;
					case AuthFailed:
						break;
					case ConnectedReadOnly:
						break;
					case SaslAuthenticated:
						break;
					case Expired:
						break;
				}
			}
		});
		countDownLatch.await();
		ZooKeeper.States state = zkClient.getState();
		switch (state) {
			case CONNECTING:
				System.out.println("ing");
				break;
			case ASSOCIATING:
				break;
			case CONNECTED:
				System.out.println("ted");
				break;
			case CONNECTEDREADONLY:
				break;
			case CLOSED:
				break;
			case AUTH_FAILED:
				break;
			case NOT_CONNECTED:
				break;
		}

		String s = zkClient.create("/ooxx", "oldData".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
		System.out.println("创建成功,返回数据为===>"+s);
		final Stat stat = new Stat();
		byte[] data = zkClient.getData("/ooxx", new Watcher() {
			public void process(WatchedEvent watchedEvent) {
				System.out.println("节点的回调"+watchedEvent.toString());
				try {
					byte[] data1 = zkClient.getData("/ooxx", this, stat);
					System.out.println("新的数据为===>"+new String(data1));
				} catch (KeeperException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}, stat);
		System.out.println("获取到到数据为===>"+new String(data));
		Stat stat1 = zkClient.setData("/ooxx", "newData".getBytes(), 0);
		Stat stat2 = zkClient.setData("/ooxx", "newData01".getBytes(), stat1.getVersion());

		Thread.sleep(55555555);



	}
}
